package main

import (
	"database/sql"
	"fmt"
	"log"

	_ "github.com/go-sql-driver/mysql" // 匿名导入
)

func main() {
	dsn := "root:@tcp(127.0.0.1)/Alpaca"
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		log.Fatalln(err)
	}
	defer db.Close()

	if err := db.Ping(); err != nil {
		log.Fatalln("数据库连接测试失败", err)
	}
	fmt.Println("成功连接到数据库")

	query := "select * from t1"
	ret, err := db.Query(query)
	if err != nil {
		log.Fatalln(err)
	}
	defer ret.Close()

	type User struct {
		Id    int
		Name  string
		Score int
	}

	var users []User
	for ret.Next() {
		var user User
		if err := ret.Scan(&user.Id, &user.Name, &user.Score); err != nil {
			log.Fatalln(err)
		}
		users = append(users, user)
		fmt.Printf("id: %v name: %v score: %v\n", user.Id, user.Name, user.Score)
	}

	if err := ret.Err(); err != nil {
		log.Fatal(err)
	}

	result, err := db.Exec("insert into t1(name,score) value(?,?)", "王五", 88)
	if err != nil {
		log.Fatalln(err)
	}

	id, err := result.LastInsertId()
	if err != nil {
		log.Fatalln(err)
	}
	fmt.Println("插入成功 id: ", id)

	affected, err := result.RowsAffected()
	if err != nil {
		log.Fatalln(err)
	}
	fmt.Println("受影响行数: ", affected)

}
